//
//  MyReleaseDemandTabVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/3.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "MyReleaseDemandTabVC.h"
#import "HomeModel.h"
#import "MyReleaseDemandCell.h"
#import "WriteRequirementTitleCell.h"
#import "ReleaseModel.h"
@interface MyReleaseDemandTabVC ()<MyReleaseDemandCellDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) NSMutableArray *editDemandArray;
@property(nonatomic,strong) NSMutableArray *demandArray;
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger pageSize;
@property(nonatomic,strong) NSDictionary  *dict;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@end
static NSString *identifierTitle = @"titleCell";
@implementation MyReleaseDemandTabVC
-(NSMutableArray *)editDemandArray
{
    if (!_editDemandArray) {
        _editDemandArray = [NSMutableArray array];
        
    }
    return _editDemandArray;
}
-(NSMutableArray *)demandArray
{
    if (!_demandArray) {
        _demandArray = [NSMutableArray array];
        
    }
    return _demandArray;
}
//- (void)viewWillAppear:(BOOL)animated
//{
//    [self refresh];
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [AFHTTPSessionManager manager];
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:@"WriteRequirementTitleCell" bundle:nil] forCellReuseIdentifier:identifierTitle];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(demandselectReleaseDemand:) name:@"demandselectReleaseDemand" object:nil];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.mj_header = header;
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMore)];
    [footer setTitle:[NSBundle bundleLocalizedStringForKey:@"footerTitle"]
            forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = [UIFont systemFontOfSize:12];
    footer.stateLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    self.tableView.mj_footer = footer;
    [header beginRefreshing];
  
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDemand:) name:@"updateDemand" object:nil];
}
-(void)updateDemand:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSString *message = [info.userInfo objectForKey:@"message"];
//    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
//    [SVProgressHUD showSuccessWithStatus:message maskType:SVProgressHUDMaskTypeBlack];
    [self refresh];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)refresh
{
    self.demandArray = nil;
    self.editDemandArray = nil;
    self.pageNum = 1;
    self.pageSize = 10;
    [self reloadInternetData];
    [self.tableView.mj_header endRefreshing];
}
-(void)reloadMore
{
    self.pageNum ++;
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    [self reloadInternetData];

}
-(void)reloadInternetData {
    
    
        NSString *pages = [NSString stringWithFormat:@"%ld",self.pageNum];
        NSString *rows = [NSString stringWithFormat:@"%ld",self.pageSize];
        
        self.dict = @{
                      @"uid":[UserDefaultsHelper readUid],
                      @"pageNum":pages,
                      @"pageSize":rows,
                      @"token":[UserDefaultsHelper readToken]
                      };
//    self.dict = @{
//                  @"uid":@"1",
//                  @"pageNum":pages,
//                  @"pageSize":rows
//                  };
        XLog(@"我发布的self.dict:%@",self.dict);
        [CustomeManager POSTWithURLIndex:44 parameters:self.dict success:^(NSDictionary *dict) {
            
        } failure:^(NSError *error) {
            
        }];
}
-(void)demandselectReleaseDemand:(NSNotification *)info
{
//    self.editDemandArray = nil;
    
    NSDictionary *dict = info.userInfo;
    XLog(@"我发布的dict:%@",dict);
    NSDictionary *date = [dict objectForKey:@"date"];
//    if (empty !=1) {
        NSArray *editDemandArray = [date objectForKey:@"editDemand"];
    if (editDemandArray.count) {
        for (NSDictionary *dict in editDemandArray) {
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dict];
            [self.editDemandArray addObject:model];
        }
//        [self.tableView.mj_header endRefreshing];
//        [self.tableView.mj_footer endRefreshing];
    }
    NSArray *demandArray = [date objectForKey:@"demand"];
    NSInteger empty = [EmptyModel stringIsNullOrEmpty:demandArray];
    if (empty !=1) {
        for (NSDictionary *dict in demandArray) {
            HomeModel *model = [HomeModel mj_objectWithKeyValues:dict];
            [self.demandArray addObject:model];
        }
        if (demandArray.count< 10) {
            self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
        }else {           
            [self.tableView.mj_footer endRefreshing];
        }
    }else {
        self.tableView.mj_footer.state = MJRefreshStateNoMoreData;
    }
    [self.tableView.mj_header endRefreshing];
    if (!self.editDemandArray.count&&!self.demandArray.count) {
        self.tableView.emptyDataSetSource = self;
        self.tableView.emptyDataSetDelegate = self;
        [self.tableView.mj_footer removeFromSuperview];
    }else {
        
    }
    [self.tableView reloadData];
    [WSProgressHUD dismiss];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.editDemandArray.count?self.editDemandArray.count+1:0;
    }else {
        return self.demandArray.count?self.demandArray.count+1:0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = @"编辑中需求";
            return cell;
        }else {
            MyReleaseDemandCell *cell = [MyReleaseDemandCell cellNibWithTableView:tableView];
            cell.indexPath = indexPath;
            cell.delegate = self;
            [cell.editingBtn setTitle:@"继续编辑" forState:UIControlStateNormal];
            [cell.editingBtn setTitleColor:[UIColor colorWithRed:151/255.0 green:193/255.0 blue:91/255.0 alpha:1] forState:UIControlStateNormal];
            if (self.editDemandArray.count) {
                HomeModel *model = self.editDemandArray[indexPath.row-1];
                cell.homeModel = model;
            }
            return cell;
            
        }
    }else {
        if (indexPath.row == 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierTitle forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.text = @"已发布需求";
            return cell;
        }else {
            MyReleaseDemandCell *cell = [MyReleaseDemandCell cellNibWithTableView:tableView];
            cell.indexPath = indexPath;
            cell.delegate = self;
            [cell.editingBtn setTitle:@"修改内容" forState:UIControlStateNormal];
            [cell.editingBtn setTitleColor:[UIColor colorWithRed:242/255.0 green:156/255.0 blue:56/255.0 alpha:1] forState:UIControlStateNormal];
            if (self.demandArray.count) {
                HomeModel *model = self.demandArray[indexPath.row-1];
                cell.homeModel = model;
            }
            return cell;
            
        }
    }
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        HomeModel *model = self.demandArray[indexPath.row-1];
        if (self.returnValueBlock){
            self.returnValueBlock(model, 0);
        };
    }
}
#pragma mark-代理:删除,编辑
- (void)myReleaseDemandCell:(MyReleaseDemandCell *)myReleaseDemandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    if (clickBtn.tag == 1) {
        NSString *aid = [NSString stringWithFormat:@"%ld",homeModel.id];
        self.dict = @{
                      @"uid":[UserDefaultsHelper readUid],
                      @"id":aid,
                      @"token":[UserDefaultsHelper readToken]
                      };
        XLog(@"self.dict:%@",self.dict);
        self.urlString = [NSString stringWithFormat:@"%@/demand/delectDemand",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            XLog(@"responseObject:%@",responseObject);
            NSString *message = [responseObject objectForKey:@"message"];
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
            [self refresh];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else if (clickBtn.tag == 2) {
        if (self.returnValueBlock){
            self.returnValueBlock(homeModel, 1);
        };
    }else {
        homeModel.show = clickBtn.selected;
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 60;
    }else {
        return 150;
    }

}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 1)];
    return headerView;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0,1)];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
//    if (section == 0) {
//        return 20;
//    }else {
        return 0.1;
//    }
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

@end
